#!/usr/bin/env python -OO
# -*- coding: utf-8 -*-

# Copyright © 2008,2009 Trust Digital Technology Laboratory, Shanghai Jiao Tong University.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author:
#   XING Dong sheng <homer.xing@gmail.com>

from __future__ import with_statement

import sys, os, threading, statvfs, pynotify

__all__ = ['T', 'TempOwn', 'isroot', 'getArch', 'ubuntuVersion', 'installed', 'filecontain', 'fileinsert', 'fileappend', 'freespace', 'notify']

class T(threading.Thread):
	"每隔60秒, 执行一次'sudo -v'"
	def __init__(self):
		threading.Thread.__init__(self)
		self.out = False
		self.live = True
	def run(self):
		i=0
		while self.live:
			os.system("sleep 1")
			i+=1
			if i%60==0 and self.out: os.system("sudo -v")
	def on(self): self.out = True
	def off(self): self.out = False
	def die(self): self.live = False

class TempOwn:
	def __init__(self,path):
		os.system('sudo touch '+path)
		os.system('sudo chown $USER:$USER %s'%path )
		self.path = path
	def __enter__(self):
		return None
	def __exit__(self, type, value, traceback):
		os.system('sudo chown root:root %s'%self.path)

# FIXME notify 能否显示十秒？
def notify(title, content):
	try:
		print content
		n=pynotify.Notification(title, content.replace('\n',' ') )
		n.show()
	except:
		pass

def isinsudo():
  return os.getuid()==0 and os.getenv("HOME")!="/root"

def isroot():
	"判断脚本是否是由root运行。如用sudo、su启动，则返回True。"
	return os.getuid()==0

def getArch():
	"获得操作系统架构，返回32表示32位操作系统，64表示64位操作系统"
	f = os.popen("uname -m")
	arch = f.read()
	f.close()
	if arch == 'x86_64\n':
		return 64
	else: #'i686'
		return 32

def ubuntuVersion():
	"获得Ubuntu版本号"
	f = open("/etc/issue.net", "r")
	version = f.read()
	f.close()
	if '9.04' in version:
		return "9.04"
	else:
		notify('BUG!',"本程序还不支持此版本的Ubuntu，请联系作者 homer.xing@gmail.com 让他加上支持。抱歉,给您填麻烦了。")
		sys.exit(0)

def installed(package):
	with os.popen("dpkg -s %s"%package, 'r') as f:
		f.readline()
		return 'installed' in f.readline()

def filecontain(path, content):
	if os.path.exists(path):
		with open(path, 'r') as f:
			return content in f.read()
	else:
		return False

def fileinsert(path, line, string):
	with open(path, "r+") as f:
		content = f.readlines()
		content.insert(line, string)
		f.seek(0,0)
		f.writelines(content)

def fileappend(path, content):
	with open(path, "r+") as f:
		f.seek(0,2)
		f.write(content)

def freespace(path):
	e = os.statvfs(path)
	return long(e[statvfs.F_BAVAIL])*long(e[statvfs.F_BSIZE])

try:
  inited
except:
  inited=True
  try:
    pynotify.init('Trusted Digital Technology')
  except:
    pass

if __name__ == "__main__":
	exit()
